package com.bawei.music.contentprovider;

import android.annotation.SuppressLint;
import android.content.Context;
import android.database.Cursor;
import android.provider.MediaStore;

import java.util.ArrayList;
import java.util.List;

/**
 * @Author : yaotianxue
 * @Time : On 2023/7/7 14:28
 * @Description : SongUtils 使用内容提供者获得手机上所有的音乐信息
 */
public class SongUtils {
//   * (1)uri:MediaStore.Audio.Media.EXTERNAL_CONTENT_URI
//     * (2)字段：TITLE：歌名   ARTIST 歌手   DURATION 总时长  DATA 地址  SIZE 大小
//
//    MediaStore.Audio.Media.TITLE,  歌名
//    MediaStore.Audio.Media.ARTIST, 歌手
//    MediaStore.Audio.Media.DURATION, 总时长
//    MediaStore.Audio.Media.DATA, 地址
//    MediaStore.Audio.Media.SIZE,  大小
//    MediaStore.Audio.Media.ALBUM_ID, 专辑封面的id
    @SuppressLint("Range")
    public static List<Song> getSongs(Context context){
        //创建集合
        List<Song> list = new ArrayList<>();
        //查询数据
        Cursor cursor = context.getContentResolver().query(MediaStore.Audio.Media.EXTERNAL_CONTENT_URI, null, null, null, null);
        if(cursor != null){
            while (cursor.moveToNext()){//遍历一条记录
                String title = cursor.getString(cursor.getColumnIndex(MediaStore.Audio.Media.TITLE));
                String artist = cursor.getString(cursor.getColumnIndex(MediaStore.Audio.Media.ARTIST));
                long duration = cursor.getLong(cursor.getColumnIndex(MediaStore.Audio.Media.DURATION));
                String data = cursor.getString(cursor.getColumnIndex(MediaStore.Audio.Media.DATA));
                long size = cursor.getLong(cursor.getColumnIndex(MediaStore.Audio.Media.SIZE));
                long id = cursor.getLong(cursor.getColumnIndex(MediaStore.Audio.Media.ALBUM_ID));
                list.add(new Song(title,artist,duration,data,size,id));
            }
            cursor.close();//防止内存泄漏
        }
        return list;

    }
}
